const koa = require("koa");
const Router = require("./router");
const cors = require("koa-cors");
const bodyParser = require("koa-bodyparser");
const mongoose = require("mongoose");
const CONFIG = require("./config/config");
const koaStatic = require('koa-static');
const path = require('path');
const koaBody = require('koa-body');
const fs = require('fs');

const app = new koa();

app.use(cors({
  credentials:true,//默认情况下，Cookie不包括在CORS请求之中。设为true，即表示服务器许可Cookie可以包含在请求中
}));


app.use(koaBody({
  formidable: {
    //设置文件的默认保存目录，不设置则保存在系统临时目录下
    uploadDir: path.resolve(__dirname, '../chat/public')
  },
  multipart: true // 支持文件上传
}));


app.use(koaStatic(
  path.resolve(__dirname, '../chat/public')
));


app.use(async (ctx, next)=> {
  ctx.set('Access-Control-Allow-Credentials',true)
  await next();
});



app.use(bodyParser());
mongoose.connect(CONFIG.mongodb, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});


Router(app);

app.listen(3000, (res, req) => {
  console.log("服务器在3000端口启动!");
});
